using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using TwitterMatic.Shared.Data;
using TwitterMatic.Shared.Domain;
using TwitterMatic.Shared;
using System.Web.Security;
using TwitterMatic.Shared.Validation;
using TwitterMatic_WebRole.Code;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace TwitterMatic_WebRole.Controllers
{
    [Authorize]
    public class TweetController : BaseController
    {
        protected IConfigurationProvider configuration;
        protected ITimedTweetRepository repository;

        protected IConfigurationProvider Configuration
        {
            get
            {
                if (configuration == null)
                {
                    configuration = new AzureConfigurationProvider();
                }
                return configuration;
            }
            set
            {
                configuration = value;
            }
        }

        protected ITimedTweetRepository Repository
        {
            get
            {
                if (repository == null)
                {
                    CloudStorageAccount cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnection");
                    CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient();
                    tableClient.CreateTableIfNotExist("TimedTweet");

                    repository = new TimedTweetRepository(tableClient);
                }
                return repository;
            }
            set
            {
                repository = value;
            }
        }

        //
        // GET: /Tweet/

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        //
        // GET: /Tweet/List

        public ActionResult List()
        {
            var tweets = Repository.RetrieveAll(this.User.Identity.Name)
                                   .Where(t => t.Archived == false)
                                   .OrderByDescending(t => t.SendOn);

            if (Request["json"] != null)
            {
                return JavaScript(JsonTimeline.Create(tweets));
            }
            return View(tweets);
        }

        //
        // GET: /Tweet/Archived

        public ActionResult Archived()
        {
            var tweets = Repository.RetrieveAll(this.User.Identity.Name)
                                   .Where(t => t.Archived == true)
                                   .OrderByDescending(t => t.SendOn);

            if (Request["json"] != null)
            {
                return JavaScript(JsonTimeline.Create(tweets));
            }
            return View(tweets);
        }

        //
        // GET: /Tweet/Create

        public ActionResult Create()
        {
            TimedTweet tweet = new TimedTweet();

            ViewData["SendOnDate"] = tweet.SendOn.ToShortDateString();
            ViewData["SendOnTime"] = tweet.SendOn.ToShortTimeString();

            return View(tweet);
        }

        //
        // POST: /Tweet/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(int UtcOffset, string SendOnDate, string SendOnTime, FormCollection collection)
        {
            TimedTweet tweet = new TimedTweet(this.User.Identity.Name);
            try
            {
                tweet.SendOn = DateTime.Parse(SendOnDate + " " + SendOnTime).AddMinutes(UtcOffset);

                // Ensure we have a valid SendOn date
                if (!TimedTweetValidation.ValidateFutureDate(tweet.SendOn))
                {
                    ModelState.AddModelError("SendOn", "The scheduled time should be in the future.");
                }

                if (this.TryUpdateModel(tweet, new string[] { "Status" }, collection.ToValueProvider()) && ModelState.IsValid)
                {
                    MembershipUser user = Membership.GetUser(this.User.Identity.Name);
                    string[] token = user.GetPassword("matic").Split(';');
                    tweet.Token = token[0];
                    tweet.TokenSecret = token[1];

                    Repository.Insert(this.User.Identity.Name, tweet);

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData["SendOnDate"] = tweet.SendOn.ToShortDateString();
                    ViewData["SendOnTime"] = tweet.SendOn.ToShortTimeString();
                    return View(tweet);
                }
            }
            catch
            {
                ViewData["SendOnDate"] = tweet.SendOn.ToShortDateString();
                ViewData["SendOnTime"] = tweet.SendOn.ToShortTimeString();
                return View(tweet);
            }
        }

        //
        // GET: /Tweet/Edit

        public ActionResult Edit(string id)
        {
            TimedTweet tweet = Repository.RetrieveById(this.User.Identity.Name, id);

            ViewData["SendOnDate"] = tweet.SendOn.ToShortDateString();
            ViewData["SendOnTime"] = tweet.SendOn.ToShortTimeString();

            return View(tweet);
        }

        //
        // POST: /Tweet/Edit

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(string id, int UtcOffset, string SendOnDate, string SendOnTime, FormCollection collection)
        {
            TimedTweet tweet = Repository.RetrieveById(this.User.Identity.Name, id);
            try
            {
                tweet.SendOn = DateTime.Parse(SendOnDate + " " + SendOnTime).AddMinutes(UtcOffset);

                // Ensure we have a valid SendOn date
                if (!TimedTweetValidation.ValidateFutureDate(tweet.SendOn))
                {
                    ModelState.AddModelError("SendOn", "The scheduled time should be in the future.");
                }

                if (this.TryUpdateModel(tweet, new string[] { "Status" }, collection.ToValueProvider()) && ModelState.IsValid)
                {
                    MembershipUser user = Membership.GetUser(this.User.Identity.Name);
                    string[] token = user.GetPassword("matic").Split(';');
                    tweet.Token = token[0];
                    tweet.TokenSecret = token[1];

                    Repository.Update(tweet);

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData["SendOnDate"] = tweet.SendOn.ToShortDateString();
                    ViewData["SendOnTime"] = tweet.SendOn.ToShortTimeString();
                    return View(tweet);
                }
            }
            catch
            {
                ViewData["SendOnDate"] = tweet.SendOn.ToShortDateString();
                ViewData["SendOnTime"] = tweet.SendOn.ToShortTimeString();
                return View(tweet);
            }
        }

        //
        // GET: /Tweet/Archive

        public ActionResult Archive(string id)
        {
            TimedTweet tweet = Repository.RetrieveById(this.User.Identity.Name, id);
            Repository.Archive(this.User.Identity.Name, tweet);

            return RedirectToAction("Index");
        }

        //
        // GET: /Tweet/Delete

        public ActionResult Delete(string id)
        {
            TimedTweet tweet = Repository.RetrieveById(this.User.Identity.Name, id);
            Repository.Delete(this.User.Identity.Name, tweet);

            return RedirectToAction("Archived");
        }
    }
}
